package cate.game.pay;

import cate.game.GameBody;
import cate.game.framework.ModuleMan;
import cate.game.role.Role;
import cate.game.util.ct.CT;
import cp.solution.business.pay.PayRecordEntity;
import cp.solution.business.pay.dto.PayDeliverResult;
import cp.solution.define.PayOrderType;
import cp.solution.rpc.RpcMsgHead;
import cp.solution.rpc.path.RpcSharePath;

/** 支付管理模块 */
public class PayManager extends ModuleMan {
    static final PayHandlerScanner SCANNER = new PayHandlerScanner();

    @Override
    public void initIndependent(GameBody game) throws Exception {
        super.initIndependent(game);
    }

    @Override
    public void initDependent() throws Exception {
        game.rpcRecv().onRequestResponseTemplate(RpcSharePath.PAY_DELIVER_P2G, PayRecordEntity.class, this::onPayDeliver);
    }

    private PayDeliverResult onPayDeliver(RpcMsgHead head, PayRecordEntity record) {
        log.info("收到支付服务器的兑现请求：{}", record);
        CT.nPayDeliverCall++;
        try {
            Role role = game.role.getRole(record.roleId);
            if(PayOrderType.OUTSIDE == record.getOrderType()) {
                PayDeliverResult r = OutsidePayHandler.exe(role, record, PayDeliverParam.normal);
                return r;
            } else {
                PayDeliverResult r = role.getPay().deliver(record, PayDeliverParam.normal);
                return r;
            }
        } catch (Exception e) {
            log.error("执行兑现支付异常", e);
            CT.nPayDeliverFail++;
            throw e;
        }
    }

    public PayCallback getPayHandler(int funcId) {
        return SCANNER.getPayHandler(funcId);
    }
}